package com.example.web.filter;

import com.example.web.entity.User;
import com.example.web.service.MenuService;
import com.example.web.service.UserService;
import com.example.web.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * JWT认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;
    
    @Autowired
    private MenuService menuService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 获取token
        String token = getTokenFromRequest(request);
        
        // 如果token为空或无效，则放行，交由后续的过滤器处理
        if (!StringUtils.hasText(token) || !jwtUtils.validateToken(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        
        // 从token中获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        
        // 如果用户名为空，则放行
        if (!StringUtils.hasText(username)) {
            filterChain.doFilter(request, response);
            return;
        }
        
        // 如果SecurityContext中已有认证信息，则放行
        if (SecurityContextHolder.getContext().getAuthentication() != null) {
            filterChain.doFilter(request, response);
            return;
        }
        
        // 获取用户信息
        User user = userService.findByUsername(username);
        if (user == null) {
            filterChain.doFilter(request, response);
            return;
        }
        
        // 获取用户权限
        List<GrantedAuthority> authorities = getUserAuthorities(user.getId());
        
        // 创建认证信息
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                username, null, authorities);
        
        // 将认证信息放入SecurityContext
        SecurityContextHolder.getContext().setAuthentication(authentication);
        
        // 放行
        filterChain.doFilter(request, response);
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
    
    /**
     * 获取用户权限
     */
    private List<GrantedAuthority> getUserAuthorities(Long userId) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        // 获取用户角色权限
        List<String> roles = userService.getRolesByUserId(userId);
        for (String role : roles) {
            if (StringUtils.hasText(role)) {
                authorities.add(new SimpleGrantedAuthority(role));
            }
        }
        
        // 获取用户菜单权限
        List<String> permissions = menuService.getPermissionsByUserId(userId);
        for (String permission : permissions) {
            if (StringUtils.hasText(permission)) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
        }
        
        return authorities;
    }
}